package com.rong.maven01demo.control;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileController {

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(String name, MultipartFile file, HttpServletRequest request) throws IOException {

        System.out.println(name);
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getContentType());

        //String path = request.getServletContext().getRealPath()是程序运行路径
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(file, path);
        return ResponseEntity.ok("上传成功");
    }

    private void saveFile(MultipartFile file, String path) throws IOException {
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }

        File file1 = new File(path + file.getOriginalFilename());
        file.transferTo(file1);
    }
}
